package ua.openmedis.web;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ua.openmedis.ServerUtils;
import ua.openmedis.dao.api.AssetGenericNameDAO;
import ua.openmedis.dao.impl.AssetGenericNameDAOImpl;

/**
 * Registering Hibernate statistic MBean
 */
public class OpenmedisServletContextListener implements ServletContextListener {

	private static final Logger log = LoggerFactory
			.getLogger(OpenmedisServletContextListener.class);

	private AssetGenericNameDAO assetGenericNameDAO = new AssetGenericNameDAOImpl();

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		try {
			log.info("Starting servlet context initialization");

			log.info("Forsing creating EntityManagerFactory...");
			ServerUtils.getEntityManager();
			log.info("Forsing creating EntityManagerFactory done ");

			log.warn("Forsing creating indexes in DB. Must be done " +
					"once after creating DB and after editing data");
			assetGenericNameDAO.indexDatabase();
			log.info("Forsing creating indexes in DB done");

		} catch (Exception e) {
			log.error("Error while initialization OpenMEDIS", e);
		}
		log.info("Servlet context was initialized");
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		log.info("Destroing servlet context");
	}

}
